/**
 * Created by inZa on 1. 10. 2014.
 *
 * Controller for managing already  roles.
 */
angular.module('aaser.controllers').controller('MappedEntitiesController', ['$scope', '$http', 'Assignment', 'Resources', 'Authorization',
    function ($scope, $http, Assignment, AaserResources, Authorization) {

       // Authorization({'classification-type': 'global', 'classification-name': 'GLOBAL', 'permission': 'CONFIGURE_AUTH'});

        $scope.entityType = 'user';
        $scope.selectedEntity = '';
        $scope.titleOfTable = 'Users';
        $scope.assignments = [];

        $scope.$watch('entityType', function () {
            switch ($scope.entityType) {
                case 'user':
                    $scope.entities = AaserResources.users.query();
                    $scope.selectedEntity = '';
                    $scope.titleOfTable = "Users";
                    $scope.assignments = [];
                    break;
                case 'group':
                    $scope.entities = AaserResources.groups.query();
                    $scope.selectedEntity = '';
                    $scope.titleOfTable = "Groups";
                    $scope.assignments = [];
                    break;
                case 'role':
                    $scope.entities = AaserResources.roles.query();
                    $scope.selectedEntity = '';
                    $scope.titleOfTable = "Roles";
                    $scope.assignments = [];
                    break;

            }
        });

        $scope.$watch('selectedEntity', function () {
            if ($scope.selectedEntity != '') {
                $scope.initAssignments();
            }
        });

        $scope.selectEntity = function (entity) {
            if (entity == $scope.selectedEntity) {
                $scope.selectedEntity = '';
            } else {
                $scope.selectedEntity = entity;
            }
        };

        $scope.isEntitySelected = function (entity) {
            return entity == $scope.selectedEntity;
        };

        $scope.deleteAssignment = function (assignment) {
            Assignment.delete({}, {'Id': assignment.id}).$promise.then(function () {
                $scope.initAssignments();
            });

        };

        $scope.initAssignments = function () {
            var assignOfEnt = {};
            var param;
            if ($scope.entityType == 'role') {
                param = $scope.selectedEntity.id;
            } else {
                param = $scope.selectedEntity.name
            }
            assignOfEnt[$scope.entityType] = param;
            $scope.assignments = Assignment.query(assignOfEnt);

        };


    }]);